﻿using GalaSoft.MvvmLight.Messaging;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Microsoft.Practices.ServiceLocation;
using PokemonGo.RocketAPI.Exceptions;
using PokemonGo.UI.Common;
using PokemonGo.UI.ViewModel;
using PokemonGo.UI.ViewModel.Messengers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PokemonGo.UI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        private MainViewModel Main;
        private SolidColorBrush defaultColorBrush = new SolidColorBrush(Colors.Black);

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += async (o, e) => ViewModelLocator.Startup();
            this.Closing += async (o, e) => ViewModelLocator.Cleanup();


            this.Loaded += MainWindow_Loaded;
            
            this.Closing += MainWindow_Closing;
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ObservableCollection<PokeClient> clients = icPoke.ItemsSource as ObservableCollection<PokeClient>;
            if (clients != null && clients.Any(a => a.IsRunning))
            {
                e.Cancel = true;
                this.ShowMessageAsync("提示", "程序正在在挂机中,是否要强制退出?", MessageDialogStyle.AffirmativeAndNegative).ContinueWith(o =>
                {
                    if (o.Result == MessageDialogResult.Affirmative)
                    {
                        Main.PokeClients?.ForEach(f => f.Stop());
                        Dispatcher.Invoke(() => this.Close());
                    }
                });
            }

        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Main = ServiceLocator.Current.GetInstance<MainViewModel>();
            RegisterMessengers();
        }
        private void RegisterMessengers()
        {
            Messenger.Default.Register<string>(this, MessengerType.Alert, o => { this.ShowMessageAsync("提示", o, MessageDialogStyle.Affirmative, new MetroDialogSettings { ColorScheme = MetroDialogColorScheme.Accented }); });
            Messenger.Default.Register<MessengerAppendMsg>(this, MessengerType.Log, AppendMsg);
            Messenger.Default.Register<Action<PokeClient>>(this, MessengerType.ShowBackpack, o =>
            {
                flyoutPokeBackpack.IsOpen = true;
                flyoutPokeBackpack.DataContext = o;
            });
            Messenger.Default.Register<PokeClient>(this, MessengerType.ComfirmRemovePokemon, async o =>
             {
                 if (o.IsRunning)
                 {
                     await this.ShowMessageAsync("提示", $"帐户[{o.ClientSettings.PtcUsername}]正在挂机中,请先停止中再删除...");
                     return;
                 }
                 var mySettings = new MetroDialogSettings()
                 {
                     AffirmativeButtonText = "确定",
                     NegativeButtonText = "取消",
                     ColorScheme = MetroDialogColorScheme.Accented
                 };

                 MessageDialogResult result = await this.ShowMessageAsync("提示", $"你确认要删除[{o.ClientSettings.PtcUsername}]帐户吗?",
                     MessageDialogStyle.AffirmativeAndNegative, mySettings);
                 if (result == MessageDialogResult.Affirmative)
                 {
                     var list = icPoke.ItemsSource as ObservableCollection<PokeClient>;
                     list?.Remove(o);
                 }
             });
        }

        private void txtMsg_TextChanged(object sender, TextChangedEventArgs e)
        {
            txtMsg.ScrollToEnd();
        }

        public void AppendMsg(MessengerAppendMsg msg)
        {
            this.Dispatcher.Invoke(() =>
            {
                if (txtMsg.Document.Blocks.Count >= 100)
                {
                    txtMsg.Document.Blocks.Clear();
                    GCUtil.ClearMemory();
                }
                var r = new Run(msg.Msg);
                r.Foreground = new SolidColorBrush(msg.ForegroundColor);
                txtMsg.Document.Blocks.Add(new Paragraph(r));
            });
        }


        private void icPoke_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            StackPanel items = (StackPanel)sender;

            ScrollViewer scroll = items.ScrollOwner;
            if (scroll != null)
            {
                int d = e.Delta;
                if (d > 0)
                {
                    scroll.LineLeft();
                }
                if (d < 0)
                {
                    scroll.LineRight();
                }
                scroll.ScrollToTop();
            }
        }
        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            if (obj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                    if (child != null && child is T)
                    {
                        return (T)child;
                    }
                    T childItem = FindVisualChild<T>(child);
                    if (childItem != null) return childItem;
                }
            }
            return null;
        }


        private void icPoke_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //var locator = App.Current.Resources.FindName("Locator");
            if (icPoke.SelectedItems.Count > 0)
            {
                flyoutPokemonUserSetting.DataContext = icPoke.SelectedItems[0];
                flyoutPokeUserSetting.IsOpen = true;
            }
        }

        private void AddNewPokeClient_Click(object sender, RoutedEventArgs e)
        {
            flyoutPokemonUserSetting.DataContext = new PokeClient(new Settings(true));
            flyoutPokeUserSetting.IsOpen = true;
            flyoutPokeUserSetting.IsOpenChanged += FlyoutPokeUserSetting_IsOpenChanged;
        }

        private void FlyoutPokeUserSetting_IsOpenChanged(object sender, RoutedEventArgs e)
        {
            if (!flyoutPokeUserSetting.IsOpen)
            {
                flyoutPokeUserSetting.IsOpenChanged -= FlyoutPokeUserSetting_IsOpenChanged;
                var pc = flyoutPokemonUserSetting.DataContext as PokeClient;
                if (pc != null && !string.IsNullOrEmpty(pc.ClientSettings.PtcUsername) && !string.IsNullOrEmpty(pc.ClientSettings.PtcPassword))
                {
                    var ic = icPoke.ItemsSource as ObservableCollection<PokeClient>;
                    if (ic.Any(a => a.ClientSettings.PtcUsername == pc.ClientSettings.PtcUsername))
                    {
                        this.ShowMessageAsync("添加失败", "帐号已在列表中");
                    }
                    else
                    {
                        ic?.Add(pc);
                    }
                }
                else
                {
                    Messenger.Default.Send("添加帐号失败, 信息不完整...", MessengerType.Alert);
                }
            }
        }
    }
}
